package org.example.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //加载主配置文件mybatis.xml
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            sqlSessionFactory = builder.build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //取得SqlSession对象
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }

    //关闭SqlSession
    public static void close(SqlSession session){
        if(null != session){
            session.close();
        }
    }

}
